package com.sunday.common.netty.e7_Websocket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebsocketServer {

    public static final int SERVER_PORT = 8833;
    public static final String SERVER_PATH = "/ws";

    public static void main(String[] args) throws InterruptedException {
        log.info("Begin to start TCP server.....");

        NioEventLoopGroup bossLoopGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossLoopGroup, workerLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new WebsocketServerChannel(SERVER_PATH));

            ChannelFuture channelFuture = bootstrap.bind(SERVER_PORT).sync();
            log.info("Websocket server started.");
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossLoopGroup.shutdownGracefully().sync();
            workerLoopGroup.shutdownGracefully().sync();
        }
    }

}
